package cat.joronya.supermanager.europeo.home;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cat.joronya.supermanager.europeo.R;
import cat.joronya.supermanager.europeo.Supermanager;
import cat.joronya.supermanager.europeo.SupermanagerPreferenceActivity;
import cat.joronya.supermanager.europeo.service.SupermanagerServiceHelper;
import cat.joronya.supermanager.europeo.service.UserDataManager;

public class HomeActivity extends Activity 
{
	private final String TAG = "supermanager";
	private Cursor cursor = null;
	private HomeObserver homeObserver = null;
	private SimpleDateFormat simpleDateFormat= null;
	
	// dialeg mostrat
	//private int dialogShown = -1;
	
	// possible progress dialogs
	private static final int ABOUT_DIALOG = 1;
	private static final int UPDATE_CHECK_PROGRESS = 2;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        
        simpleDateFormat = new SimpleDateFormat("EEEE d/MM, HH:mm'h'");
        
        // set default values in preferences not setted by user
        PreferenceManager.setDefaultValues(this,
        		R.xml.preferences, 
        		false);
        
        cursor = getContentResolver().query(Supermanager.Home.CONTENT_URI, 
        		Supermanager.Home.PROJECTION, 
           		null,
           		null,
                Supermanager.Home.DEFAULT_SORT_ORDER);
        
        homeObserver = new HomeObserver(new Handler());
        
        getContentResolver().registerContentObserver(Supermanager.Home.CONTENT_URI, 
        		false, homeObserver);
        
        // en background fem el check
        new Thread(){
        	public void run(){
        		// perform check, if we're up to date then dismiss and continue
        		if( !UserDataManager.appNeedsUpdate(HomeActivity.this) )
        		{
        			Log.d(TAG,"HomeActivity userDataManager: app doesn't need update");
        			return;
        		}
        		
        		Log.d(TAG,"HomeActivity userDataManager: app needs update!");
        		
        		// cridar refresh al REST method
           		SupermanagerServiceHelper.getInstance(HomeActivity.this).fullUpdate(null, true);
        	}
        }.start();
    }
    
    @Override
	protected void onResume() 
    {
    	// update home fields
    	updateHomeFields();
    	
		super.onResume();
	}

	@Override
	protected void onDestroy() 
    {
    	getContentResolver().unregisterContentObserver(homeObserver);
		super.onDestroy();
	}
	
	/**
     * Metode on creem el/s dialeg de la activity.
     * Nomes en tenim un, passem del id.
     */
    @Override
    public Dialog onCreateDialog(int id)
    {
    	Log.d(TAG, "HomeActivity.onCreateDialog("+id+")");
    	
		//dialogShown = id;
		Dialog dialog = null;
    	switch(id)
    	{
    		case UPDATE_CHECK_PROGRESS:
    			dialog = ProgressDialog.show(this, "", 
    					getResources().getString(R.string.home_progress_update_check), true);
    			dialog.setCancelable(false);
    			break;
    		default:
    		case ABOUT_DIALOG:
    			AlertDialog.Builder builder;
    			LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
    			View layout = inflater.inflate(R.layout.about,null);
    			
    			builder = new AlertDialog.Builder(this);
    			builder.setView(layout);
    			dialog = builder.create();
    			break;
    	}
    	
    	return dialog;
    }
    
    public void openLink(View view) 
	{
    	// throw CONTENT_URI of web
    	Intent i = new Intent(Intent.ACTION_VIEW);
    	i.setData(Uri.parse(getString(R.string.about_link)));
    	startActivity(i);
	}

	/**
     * Update fields.
     */
    private void updateHomeFields()
    {
    	final TextView day = (TextView) findViewById(R.id.home_day);
    	final TextView duetimeLabel = (TextView) findViewById(R.id.home_label);
    	final LinearLayout duetimeRow = (LinearLayout) findViewById(R.id.home_duetime_row);
		final TextView duetime = (TextView) findViewById(R.id.home_duetime);
		final WebView homeInfo = (WebView) findViewById(R.id.home_info);
		final ImageView status = (ImageView) findViewById(R.id.home_status);

		if( cursor.moveToFirst() )
        {   
    		duetimeRow.setVisibility(View.GONE);
			day.setText(getString(R.string.home_day, cursor.getString(1)));
			Timestamp duetimestamp = null;
    		Integer duetimeDay = null;
    		
    		try{
        		int homeStatus = cursor.getInt(2);
        		if( homeStatus == Supermanager.OPEN_STATUS )
        		{        			
        			long timestamp = cursor.getInt(4);
        			duetimestamp = new Timestamp(timestamp*1000);
        			duetimeDay = cursor.getInt(5);
        			Log.d(TAG,"HomeActivity duetimeValue: "+duetimestamp+
        					", getTime(): "+duetimestamp.getTime()+
        					", cursor.getInt(4): "+timestamp);
        		
        			if( duetimestamp != null )
        			{
        				duetimeLabel.setText(getString(R.string.home_label,
        						duetimeDay.toString()));
        				duetime.setText(getString(R.string.home_duetime, 
        						simpleDateFormat.format(duetimestamp.getTime())));
        				duetimeRow.setVisibility(View.VISIBLE);
        			}
        		}
    		}
    		catch(Exception e){
    			Log.d(TAG, "HomeActivity: duetimeValue or duetimeDay are NULL");
    		}
    		
    		homeInfo.loadDataWithBaseURL("http://supermanager.acb.com", cursor.getString(3), "text/html","utf-8", "");
    		switch(new Integer(cursor.getString(2)))
    		{
    			case Supermanager.CLOSED_STATUS:
    				status.setImageResource(R.drawable.closed);
    				break;
    			case Supermanager.OPEN_NO_CHANGES_STATUS:
    				status.setImageResource(R.drawable.open_changes_closed);
    				break;
    			case Supermanager.OPEN_STATUS:
    				status.setImageResource(R.drawable.open);
    				break;
    			case Supermanager.AUTH_ERROR_STATUS:
    			case Supermanager.OTHER_ERROR_STATUS:
    			case Supermanager.CONNECTIVITY_ERROR_STATUS:
    				status.setImageResource(R.drawable.error);
    				break;
    			default:
    				status.setImageResource(R.drawable.refresh);
    		}
        }
		else
		{
    		day.setText(getString(R.string.home_day, ""));
    		duetime.setText(getString(R.string.home_duetime, ""));
    		homeInfo.loadData(getString(R.string.home_info, ""),"text/html","ISO-8859-1");
    		status.setImageResource(R.drawable.refresh);		
		}
    }
    
	/**
	 * Handle change of orientation.
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) 
	{
		Log.d(TAG,"HomeActivity.onConfigurationChanged called");
		super.onConfigurationChanged(newConfig);
		setContentView(R.layout.home);

		// actualitzem dades
		updateHomeFields();
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle item selection
        switch (item.getItemId()) 
        {
        	case R.id.refresh:
				// cridar refresh al REST method
           		SupermanagerServiceHelper.getInstance(this).fullUpdate(null,true);
				return true;
        	case R.id.settings:
        		// llancem Preferences activity
        		Intent settingsActivity = new Intent(getBaseContext(),
        				SupermanagerPreferenceActivity.class);
        		startActivity(settingsActivity);
        		return true;
        	case R.id.about:
        		// show about progress
        		showDialog(ABOUT_DIALOG);
        		
        		return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }
    
    /**
     * Observer to register Home content and keep updated
     * HomeActivity content.
     * @author pol
     *
     */
    class HomeObserver extends ContentObserver
    {
		public HomeObserver(Handler handler) 
		{
			super(handler);
		}
    	
		@Override
		public boolean deliverSelfNotifications() 
		{
			return false;
		}

		@Override
		public void onChange(boolean selfChange) 
		{
			super.onChange(selfChange);
			updateHomeFields();
		}
    }
    
}
